<script>
export default {
  name: "superMapForCesiumBaseMap",
};
</script>
<script setup>
import { onMounted, ref, onUnmounted, defineEmits } from "vue";
import URL_CONFIG from "@/assets/js/URL_CONFIG.js";
import superMapForCesiumVariableObj, {
  cameraSetViewToChina,
  cameraSetViewToQL_line,
  entitieAdd,
} from "@/utils/globalVariable/superMapForCesiumBaseMap.js";

const emits = defineEmits(["entityClick", "S3MClick", "stationClick"]);

const cesiumContainer = ref(null);
let viewer = null;

/**
 *  Cesium 使用原生全局导入
 */
const initCesium = () => {
  // 确保 DOM 容器已渲染
  if (cesiumContainer.value) {
    // 初始化 SuperMap iClient3D for Cesium 查看器
    window.CesiumViewer =
      superMapForCesiumVariableObj.viewer =
      viewer =
        new Cesium.Viewer(cesiumContainer.value, {
          //创建地形服务提供者的实例，url为SuperMap iServer发布的TIN地形服务
          // terrainProvider: new Cesium.CesiumTerrainProvider({
          //   url: URL_CONFIG.SiChuan_TERRAIN,
          //   isSct: true, //地形服务源自SuperMap iServer发布时需设置isSct为true
          //   invisibility: true,
          // }),
          terrainProvider: new Cesium.CesiumTerrainProvider({
            url:
              iserverOrigin +
              "/iserver/services/3D-local3DCache-HeBingDEMHuanCun/rest/realspace/datas/%E5%90%88DEM",
            isSct: true, //地形服务源自SuperMap iServer发布时需设置isSct为true
            invisibility: true,
          }),
          baseLayerPicker: false,
          geocoder: false,
          homeButton: false,
          infoBox: false,
          sceneModePicker: false,
          selectionIndicator: false,
          timeline: false,
          navigationHelpButton: false,
        });

    //添加SuperMap iServer发布的影像服务
    const yxImageryLayer = viewer.imageryLayers.addImageryProvider(
      new Cesium.SuperMapImageryProvider({
        url: iserverOrigin + "/iserver/services/map-NAVI_QG/rest/maps/NAVI_QG",
        name: "影像",
      })
    );
    // 将影像放置到全局模块
    superMapForCesiumVariableObj.imageryLayers.yxImageryLayer = yxImageryLayer;

    // 全国矢量底图
    const qgsldt = viewer.imageryLayers.addImageryProvider(
      new Cesium.SuperMapImageryProvider({
        url:
          iserverOrigin +
          "/iserver/services/map-BaseMap/rest/maps/%E5%9B%BE%E5%B1%82/",
        name: "全国矢量底图",
      })
    );

    qgsldt.show = false;
    superMapForCesiumVariableObj.imageryLayers.qgsldt = qgsldt;

    // 全国线路
    const qgxl = viewer.imageryLayers.addImageryProvider(
      new Cesium.SuperMapImageryProvider({
        url: iserverOrigin + "/iserver/services/map-QGXL/rest/maps/layer/",
        name: "全国线路",
      })
    );

    superMapForCesiumVariableObj.imageryLayers.qgxl = qgxl;

    // 衢丽铁路
    // const qltl = viewer.imageryLayers.addImageryProvider(
    //   new Cesium.SuperMapImageryProvider({
    //     url: iserverOrigin + "/iserver/services/map-JingGuiYuanZuoLi/rest/maps/%E5%9B%BE%E5%B1%82/",
    //     name: "衢丽铁路",
    //   })
    // );

    // superMapForCesiumVariableObj.imageryLayers.qgxl = qltl;

    const scene = viewer.scene;

    // 加载衢丽铁路 MVT 实现可点击图层
    scene.addVectorTilesMap({
      url:
        iserverOrigin +
        "/iserver/services/map-mvt-JingGuiYuanQuLiShiLiangWaPian/restjsr/v1/vectortile/maps/%E7%BB%8F%E8%A7%84%E9%99%A2%E8%A1%A2%E4%B8%BD%E7%9F%A2%E9%87%8F%E7%93%A6%E7%89%87",
      canvasWidth: 512,
      name: "testMVT",
      viewer: viewer,
    });

    // 加载 S3M
    try {
      scene
        .open(
          iserverOrigin +
            "/iserver/services/3D-local3DCache-SuZhouBeiZhan4326/rest/realspace"
        )
        .then((layer) => {
          window.layer = layer[0];
          layer[0].style3D.bottomAltitude = -190;

          setTimeout(() => {
            cameraSetViewToQL_line();
          }, 500);
        });
    } catch (e) {}

    // 设置鼠标事件
    superMapForCesiumVariableObj.handler = new Cesium.ScreenSpaceEventHandler(
      viewer.scene.canvas
    );
    cesiumSreenSpaceEventHandler(superMapForCesiumVariableObj.handler, scene);

    viewer.selectedEntityChanged.addEventListener(function (entity) {
      const selectEntity = viewer.selectedEntity;
      //  layerID: "车站点3857@经规院#1(0_24)"
      console.log(selectEntity);

      if (
        selectEntity &&
        selectEntity.layerID &&
        (selectEntity.layerID.includes("车站点") ||
          selectEntity.layerID.includes("桥面") ||
          selectEntity.layerID.includes("隧道面"))
      ) {
        const key = entity.pickResult.layerID;
        const properties = entity.pickResult[key][0].feature.properties;
        debugger;
        emits("stationClick", properties);
      }
    });
    // 初始化位置
    cameraSetViewToQL_line();

    // 测试视口位置
    // viewer.scene.camera.setView({
    //   destination: new Cesium.Cartesian3(
    //     -1206939.1925299785,
    //     5337998.241228442,
    //     3286279.2424502545
    //   ),
    //   orientation: {
    //     heading: 1.4059101895600987,
    //     pitch: -0.20917672793046682,
    //     roll: 2.708944180085382e-13,
    //   },
    // });

    // 加载一个点位做测试
    // entitieAdd(
    //   viewer,
    //   116.1590182613415,
    //   39.21417558881025,
    //   false)
  }
};

// 绑定事件
const cesiumSreenSpaceEventHandler = (handler, scene) => {
  handler.setInputAction(function (movement) {
    // 获取鼠标点击位置的实体
    const pickedObject = viewer.scene.pick(movement.position);

    // 判断是否选中了 Entity
    debugger;
    if (
      Cesium.defined(pickedObject) &&
      pickedObject.id instanceof Cesium.Entity
    ) {
      const entity = pickedObject.id;
      if (entity.metadata && entity.metadata.type) {
        emits("entityClick", entity);
      }
      window._messageIEvent.source.postMessage(
        {
          type: "CHILD_REPLY",
          data: entity.metadata,
        },
        window._messageIEvent.origin
      );
    }

    // 判断是不是选中了 S3M 模型 name "苏州北站4326"
    if (
      pickedObject &&
      pickedObject.id &&
      pickedObject.primitive.name === "苏州北站4326"
    ) {
      emits("S3MClick", pickedObject);
    }

    // 点击了地图某位置返回坐标
    const result = scene.pickPosition(movement.position);
    console.log(result);

    // 获取当前鼠标点击的坐标位置。
    const ray = viewer.camera.getPickRay(movement.position);
    const caryesian = viewer.scene.globe.pick(ray, viewer.scene);

    if (caryesian) {
      const cartographic = Cesium.Cartographic.fromCartesian(caryesian);
      console.log(cartographic);

      const longitude = Cesium.Math.toDegrees(cartographic.longitude);
      const latitude = Cesium.Math.toDegrees(cartographic.latitude);
      console.log(longitude, latitude);
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
};

// 解除事件绑定
const cesiumSreenSpaceEventHandlerRemove = (handler) => {
  // 移除特定的事件监听
  handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);

  // 完全销毁
  // handler.destroy();
};

onMounted(() => {
  initCesium();
});

onUnmounted(() => {
  // 清理资源
  if (viewer) {
    viewer.destroy();
    viewer = null;
  }
});
</script>

<template>
  <div class="cesium-container" ref="cesiumContainer"></div>
</template>

<style scoped lang="less">
.cesium-container {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 0;
}

:deep(.cesium-viewer-navigationContainer) {
  top: auto;
  bottom: 0;
  display: none !important;
}

:deep(.cesium-viewer-bottom) {
  display: none !important;
}
</style>
